import lodash from 'lodash'

export function buildTreeData(data, options, change) {
  if (!(data instanceof Array) || data.length === 0) {
    return []
  }
  if (!options) {
    options = {
      id: 'id',
      pid: 'pid',
      children: 'children'
    }
  } else {
    if (!options.pid) {
      return []
    }
    if (!options.id) {
      return []
    }

    if (!options.children) {
      options.children = 'children'
    }
  }

  if (!change) {
    change = item => item
  }

  const temp = {}
  const roots = []
  let i, p, children

  for (i = 0; i < data.length; i++) {
    temp[data[i][options.id]] = lodash.assignIn({}, data[i])
  }

  for (const key in temp) {
    p = temp[temp[key][options.pid]]
    if (p && p[options.id] !== p[options.pid]) {
      children = p[options.children]
      if (!children) {
        children = []
        p[options.children] = children
      }
      children.push(temp[key])
    } else {
      roots.push(temp[key])
    }
  }
  return changeTree(roots, change)
}

function changeTree(data, change) {
  const result = []
  for (let i = 0; i < data.length; i++) {
    result[i] = change(data[i])
    if (data[i].children) {
      result[i].children = changeTree(data[i].children, change)
    }
  }
  return result
}
